import Taro from "@tarojs/taro";

interface ResBody {
  code: number;
  data: any;
  msg: string;
}

export const request = async (opt: Taro.request.Option) => {
  opt.url = process.env.TARO_APP_BASE_API + opt.url;
  return new Promise<ResBody>((resolve) => {
    const token = Taro.getStorageSync("token");
    Taro.request({
      ...opt,
      header: {
        Authorization: token,
        ...opt.header,
      },
    })
      .then((response) => {
        if (response.statusCode === 401) {
          Taro.removeStorage({ key: "token" });
          Taro.navigateTo({ url: "/pages/index/index" });
          return;
        }
        resolve(response.data);
      })
      .catch((_) => {
        Taro.showToast({
          title: "网络错误",
          icon: "error",
          duration: 30000,
        });
      });
  });
};
